import React, { useState, useEffect, useMemo } from 'react'
import { ColumnProps, Modal, Tag } from '@kedacom/react-next'
import { fetchGetReservationLog } from '@/api/sysLog'
import { ReservationLogRequestParam } from '@/api/sysLog/interface'
import { ReservationLogData } from '../interface'
import Alert, { confirmModal } from '@/components/Alert'
import dayjs from '@/plugins/dayjs'
import { transFetchReservationLogData } from '../translate'
import { API_MEETING_PREFIX } from '@/utils/constant'
import useLock from '@/hooks/useLock'
import { t } from 'i18next'

const pageSize = 20

export default function useService() {
	const defaultParams: ReservationLogRequestParam = {
		count: pageSize,
		start: 0,
		operator: '',
		operational: '',
		start_date: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
		end_date: dayjs().format('YYYY-MM-DD'),
		order: 1,
	}
	const [data, setData] = useState<ReservationLogData[]>([])
	const [total, setTotal] = useState(0)
	const [isSearch, setIsSearch] = useState(false)
	const [open, setOpen] = useState(false)
	const [curData, setCurData] = useState<ReservationLogData | null>(null)
	const [params, setParams] = useState<ReservationLogRequestParam>(defaultParams)
	const pager = useMemo(() => {
		return { page: params.start / pageSize + 1, size: pageSize, total }
	}, [params.start, pageSize, total])

	useEffect(() => {
		queryData(params, true)
	}, [])

	const columns: ColumnProps<ReservationLogData>[] = [
		{
			title: t('操作时间'),
			dataKey: 'operating_time',
			sort: params.order ? 'desc' : 'asc',
			onSort: (e, sort) => {
				let newParams = { ...params }
				newParams.order = sort === 'desc' ? 1 : 0
				newParams.start = 0
				queryData(newParams)
				setParams(newParams)
			},
			width: 186,
		},
		{ title: t('操作用户'), dataKey: 'operator', width: 164 },
		{ title: t('登录的IP地址'), dataKey: 'operator_ip', width: 155 },
		{ title: t('操作内容'), dataKey: 'operational' },
		{
			title: t('操作结果'),
			dataKey: 'operation_result',
			width: 135,
		},
		{
			title: t('完整性校验'),
			dataKey: 'integrity_check',
			width: 135,
		},
		{
			title: t('操作'),
			dataKey: 'action',
			render: (rowData) => {
				return <Tag onClick={() => getLogDetail(rowData)}>{t('详情')}</Tag>
			},
			width: 88,
		},
	]

	const getLogDetail = (data: ReservationLogData) => {
		setOpen(true)
		setCurData(data)
	}

	const changeParam = (data: ReducerMaker<ReservationLogRequestParam>) => {
		const { type, payLoad } = data
		switch (type) {
			case 'operational':
				setParams({ ...params, operational: payLoad })
				break
			case 'operator':
				setParams({ ...params, operator: payLoad })
				break
			case 'start_date':
				setParams({ ...params, start_date: payLoad })
				break
			case 'end_date':
				setParams({ ...params, end_date: payLoad })
				break
			case 'order':
				setParams({ ...params, order: payLoad })
				break
			case 'start':
				setParams({ ...params, start: payLoad })
				break
		}
	}

	const onSearch = () => {
		let newParams = { ...params, start: 0 }
		queryData(newParams)
		setParams(newParams)
		setIsSearch(true)
	}

	const queryData = useLock(async (param: ReservationLogRequestParam, isInit?: boolean) => {
		await fetchGetReservationLog(param).then((res) => {
			if (res) {
				let data = transFetchReservationLogData(res.data)
				setData(data)
				setTotal(res.total)
			} else {
				isInit ? Alert(t('获取综合日志失败！')) : setIsSearch(false)
			}
		})
	})

	const resetSettingParam = () => {
		setIsSearch(false)
		setParams(defaultParams)
		queryData(defaultParams)
	}

	const onPageChange = (pageIndex: number, pageSize: number) => {
		let start = (pageIndex - 1) * pageSize
		queryData({ ...params, start })
		changeParam({ type: 'start', payLoad: start })
	}

	const exportLog = () => {
		confirmModal({
			msg: t('导出数据需要等待较长的时间，确定要执行吗？'),
			onOk: () => {
				let url =
					API_MEETING_PREFIX +
					`/meeting_logs/export?operator=${params.operator}&operational=${params.operational}&start_date=${params.start_date}&end_date=${params.end_date}&order${params.order}&count=${params.count}&start=${params.start}`
				window.location.href = url
			},
		})
	}

	return {
		/** table columns */
		columns,
		/** 列表数据 */
		data,
		/** 搜索请求参数 */
		params,
		/** 是否处于搜索状态 */
		isSearch,
		/** 分页器参数 */
		pager,
		/** 详细窗口是否打开 */
		open,
		/** 当前选中的日志数据 */
		curData,
		/** 详细窗口是否打开方法 */
		setOpen,
		/** 修改搜索请求参数 */
		changeParam,
		/** 请求方法 */
		onSearch,
		/** 重置搜索请求参数 */
		resetSettingParam,
		/** 分页回调 */
		onPageChange,
		/** 导出方法 */
		exportLog,
	}
}
